package com.pl.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;


/**
 * 通过ApplicationContextAware接口获取spring bean的工具类
 *
 * @author shent
 */
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }

    /**
     * 通过 类型 获取 bean
     *
     * @param requiredType 类型
     * @param <T>          T
     * @return bean
     */
    public static <T> T getBean(Class<T> requiredType) {
        return getContext().getBean(requiredType);
    }

    /**
     * 通过 名称以及类型 获取 bean
     *
     * @param name         名称
     * @param requiredType 类型
     * @param <T>          T
     * @return bean
     */
    public static <T> T getBean(String name, Class<T> requiredType) {
        return getContext().getBean(name, requiredType);
    }


}
